package com.jhws.business.repair.api;

import com.alibaba.fastjson.JSON;
import com.jhws.business.aliyun.service.OSSClientService;
import com.jhws.business.property.service.PropertyService;
import com.jhws.business.repair.bo.Repair;
import com.jhws.business.repair.bo.RepairConstant;
import com.jhws.business.repair.bo.RepairUpdateData;
import com.jhws.business.repair.service.RepairService;
import com.jhws.common.base.bo.JsonRespData;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@SuppressWarnings("Duplicates")
@Controller
@RequestMapping("/v2/repair")
public class RepairApi {
    @Resource
    private RepairService repairService;
    @Resource
    private PropertyService propertyService;
    @Resource
    private OSSClientService ossClientService;
    /**
     * 提交报修api接口
     *
     * @param repair
     * @return
     */
    @RequestMapping("putRepair")
    @ResponseBody
    public JsonRespData putRepair(Repair repair) throws Exception {
        Long now = System.currentTimeMillis();
        repair.setState(RepairConstant.REPAIR_STATE_UNTREATED);
        List<String> urls = new ArrayList<>();
        List<String> tempUrls = JSON.parseArray(repair.getImageUrls(), String.class);
        for (String url : tempUrls) {
            String fileName = FilenameUtils.getName(url);
            String destKey = "cms/file/" + fileName;
            ossClientService.gerneralCopyFile(url, destKey);
            urls.add(destKey);
        }
        repair.setImageUrls(JSON.toJSONString(urls));
        repair.setTimestamp(now);
        repairService.saveRepair(repair);
        propertyService.notifyStaffAppModuleEvent(repair.getCommCode(), RepairUpdateData.REPAIR_PROPERTY,now,"有新的报修需要处理","");
        return new JsonRespData("", 1, "");
    }

    /**
     * 查询报修接口
     *
     * @param state
     * @param ownerCode
     * @return
     * @throws Exception
     */
    @RequestMapping("queryRepairList")
    @ResponseBody
    public JsonRespData queryRepairList(int state, String ownerCode) throws Exception {
        List<Map<String, Object>> list = repairService.queryRepairListApi(state, ownerCode);
        return new JsonRespData("", 1, list);
    }

    @RequestMapping("deleteRepair")
    @ResponseBody
    public JsonRespData deleteRepair(long id) {
        repairService.deleteRepairApi(id);
        return new JsonRespData("", 1, "");
    }
}
